import * as echarts from 'echarts'
import type { ECharts } from 'echarts'
import _ from 'lodash'

export function reSize(chart: ECharts | null) {
  let $_sidebarElm = ref<Element>(document.getElementsByClassName('sidebar-container')[0])
  const $_resizeHandler = _.debounce(() => {
    if (chart) {
      chart?.resize()
    }
  }, 100)
  const $_initResizeEvent = () => {
    window.addEventListener('resize', $_resizeHandler)
  }
  const $_destroyResizeEvent = () => {
    window.removeEventListener('resize', $_resizeHandler)
  }
  const $_sidebarResizeHandler = (e: any) => {
    if (e.propertyName === 'width') {
      $_resizeHandler()
    }
  }
  const $_initSidebarResizeEvent = () => {
    $_sidebarElm && $_sidebarElm.value.addEventListener('transitionend', $_sidebarResizeHandler)
  }
  const $_destroySidebarResizeEvent = () => {
    $_sidebarElm && $_sidebarElm.value.removeEventListener('transitionend', $_sidebarResizeHandler)
  }
  $_initResizeEvent()
  $_initSidebarResizeEvent()

  onBeforeMount(() => {
    $_destroyResizeEvent()
    $_destroySidebarResizeEvent()
  })

  onActivated(() => {
    $_initResizeEvent()
    $_initSidebarResizeEvent()
  })
  onDeactivated(() => {
    $_destroyResizeEvent()
    $_destroySidebarResizeEvent()
  })
}